import {createRouter, createWebHistory, Router as VueRouter, RouteRecordRaw} from 'vue-router'
import routes from "./routes.ts"
import ngr from 'nprogress'
import 'nprogress/nprogress.css'
import {TITLE} from './proxy.d'
ngr.configure({
    showSpinner: false //是否显示加载ico
})
export declare interface Router extends VueRouter {
    find(path: string): RouteRecordRaw | undefined

    append(data: any[] | any): void

    [key: string]: any
}
const router: Router = createRouter({
    history: createWebHistory(),
    routes
}) as Router

/**
 * 组件加载后
 */
router.beforeResolve(() => {
    const el = document.getElementById('Loading')
    if (el) {
        el.style.display = 'none'
    }
})

/**
 * 清空路由
 */
router.clear = () => {
    let normalized = router.getRoutes()
    normalized.forEach((e:any) => {
        if (e.name && e.meta['dynamic']) {
            router.removeRoute(e.name)
        }
    })
}

export function pageTitle(title: any): string {
    return title ? `${TITLE} - ${title}` : `${TITLE}`
}

/**
 * 令牌key
 */
const TOKEN_KEY:string = 'token'

export function GETTOKEN() {
    return sessionStorage.getItem(TOKEN_KEY)
}
export function SETTOKEN(token:string) {
    sessionStorage.setItem(TOKEN_KEY, token)
}
export function SETUSERINFO(info:any) {
    sessionStorage.setItem('userInfo',JSON.stringify(info))
}
export function GETUSERINFO() {
    return sessionStorage.getItem('userInfo')
}

/**
 * 路由守卫
 */
router.beforeEach(async (to, from, next) => {
    ngr.start()
    document.title = pageTitle(to.meta.title)
    const token = GETTOKEN()
    if(token){
        // next()
        if (to.path == '/') {
            next('/info')
        }else{
            next()
        }
    }else{
        // next()
        if (to.path == '/'){
            next()
        }else{
            next('/')
        }
    }
    from.fullPath
})

/**
 * 后置导航守卫
 */
router.afterEach(() => {
    ngr.done()
})
export default router